<template>
	<view class="">
		<!-- Header -->
		<view class="header bg-white">
			<u-search placeholder="请输入商品名称" :show-action="false" @change="change(current)" v-model="keyword"></u-search>
		</view>

		<!-- Nav -->
		<view class="nav bg-white">
			<u-tabs name="name" :show-bar="false" :list="list" count="cate_count" :is-scroll="true" :current="current"
				@change="change" active-color="#40AFFA" />
		</view>
		<!-- Section -->
		<view class="section" :style="{'height': height}">
			<swiper :duration="400" style="height: 100%; overflow: hidden;" @change="change" :current="current">
				<swiper-item v-for="(items, index) in list" :key="index">
					<view v-show="index == current">
						<mescroll-uni bottom="220rpx" ref="mescrollRef" top="0rpx" height="100%" @init="mescrollInit"
							@up="upCallback" :up="upOption" @down="downCallback">
							<view class="title muted sm">
								共{{count}}笔订单
							</view>

							<block v-for="(items2, index2) in items.lists" :key="index2">
								<order-card :data="items2">

									<template v-if="items2.edit_address_btn">
										<router-link :to="'/pages/address_edit/address_edit?id='+items2.id">
											<button class="btn hollow br60 flex row-center normal">修改地址</button>
										</router-link>
									</template>
									<template v-if="items2.content_btn">
										<router-link :to="'/pages/order_detail/order_detail?id='+items2.id">
											<button class="btn solid br60 flex row-center normal">查看内容</button>
										</router-link>
									</template>
									<template v-if="items2.shop_cancel_btn">
										<button class="btn hollow br60 flex row-center normal"
											@click="openFunc(items2, 'close')">取消订单</button>
									</template>
									<template v-if="items2.to_ship_btn">
										<button class="btn solid br60 flex row-center normal"
											@click="toDispath(items2.id)">去发货</button>
									</template>
									<!-- <template v-if="items2.isPrint">
										<button @click="pickUpOnce(items2.id)"
											class="btn solid br60 flex row-center normal">打印订单</button>
									</template> -->
									<template v-if="items2.take_btn">
										<button class="btn solid br60 flex row-center normal"
											@click="openFunc(items2, 'confirm')">确认收货</button>
									</template>
									<template v-if="items2.delivery_btn">
										<button class="btn hollow br60 flex row-center normal"
											@click="openFunc(items2, 'recycle')">查看物流</button>
									</template>
									<template v-if="items2.del_btn">
										<button class="btn hollow br60 flex row-center normal"
											@click="openFunc(items2, 'del')">删除</button>
									</template>
									<template v-if="items2.to_verification_btn">
										<router-link :to="'/pages/verification_order/verification_order'">
											<button class="btn solid br60 flex row-center normal">去核销</button>
										</router-link>
									</template>
								</order-card>
							</block>

						</mescroll-uni>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<modal height="200rpx" v-model="close" @confirm="orderSetting">
			<view class="black n" style="height: 200rpx;">
				确认取消该订单吗?
			</view>
		</modal>

		<modal height="200rpx" v-model="del" @confirm="orderSetting">
			<view class="black nr" style="height: 200rpx;">
				确认删除该订单吗?
			</view>
		</modal>

		<modal height="200rpx" v-model="confirm" @confirm="orderSetting">
			<view class="black nr" style="height: 200rpx;">
				确认用户已收到货？请谨慎处理！
			</view>
		</modal>

		<modal height="200rpx" :cancelShow="false" v-model="recycle">
			<view class="black nr" style="height: 200rpx;">
				<view class="m-t-40">快递公司： {{logistics.shipping_name}}</view>
				<view class="m-t-20">快递公司： {{logistics.invoice_no}} <text class="copy"
						@click="copy(logistics.invoice_no)">复制</text></view>
			</view>
		</modal>

		<u-toast ref="uToast" />
		<tabBar :currentPagePath="path"></tabBar>
	</view>
</template>


<script>
	import PrinterJobs from '@/common/cjn-print/printerjobs.js'
	import printerUtil from '@/common/cjn-print/printerutil.js'
	import util from '@/common/cjn-print/util.js'
	import drawQrcode from '@/common/cjn-print/weapp.qrcode.esm.js'
	// import Bluetooth from '@/common/cjn-print/bluetooth.js'
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
	// let bluetooth = new Bluetooth();
	import {
		apiOrderList,
		apiOrderClose,
		apiOrderConfirm,
		apiOrderLogistics,
		apiOrderDelete,
		apiOrderDelivery,
		apiGetBar,
		getNewRemind
	} from '@/api/order'
	import {
		debounce,
		copy,
		audibleAlert
	} from "@/utils/tools.js"
	export default {
		mixins: [MescrollMixin],
		data() {
			return {
				path: '', //页面路径
				isOpenBle: false, //是否已经打开蓝牙，默认为false
				devicesList: [], //设备列表
				serviceList: [], //服务列表
				deviceId: "", //设备
				serviceId: "", //设备服务
				notifyId: "", //特征值
				writeId: "", //传输数据特征值
				height: '100%',

				keyword: '',
				list: [{
						name: '全部',
						type: 'all',
						cate_count: 0,
						lists: []
					},
					{
						name: '待付款',
						type: 'pay',
						cate_count: 0,
						lists: [{
							id: 0,
							to_ship_btn: true,
						}]
					},
					{
						name: '待发货',
						type: 'delivery',
						cate_count: 0,
						lists: []
					},
					{
						name: '待收货',
						type: 'receiving',
						cate_count: 0,
						lists: []
					},
					{
						name: '已完成',
						type: 'finish',
						cate_count: 0,
						lists: []
					},
					{
						name: '已取消',
						type: 'close',
						cate_count: 0,
						lists: []
					}
				],
				current: 0,
				count: 0,

				action: '',

				close: false,
				del: false,
				confirm: false,
				recycle: false,

				// 物流
				logistics: {
					shipping_name: '-',
					invoice_no: ''
				},

				upOption: {
					empty: {
						icon: '/static/images/empty/order.png',
						tip: '暂无相关订单！', // 提示
						fixed: true,
						top: "200rpx",
					}
				},
			}
		},
		//页面卸载是关闭蓝牙链接
		onUnload() {
			console.log('关闭蓝牙连接')
			// bluetooth.closeBLEConnection();
			// bluetooth.closeBluetoothAdapter();
		},
		onLoad() {
			var pages = getCurrentPages()
			this.path = pages[pages.length - 1].route
			// bluetooth.openBluetoothAdapter();
			// this.startBluetoothDeviceDiscovery()
		},
		// onShow() {
		// 	// if (this.$Route.query.curId) {
		// 	// 	this.current = Number(this.$Route.query.curId)
		// 	// 	console.log(99, this.current)
		// 	// }
		// },
		methods: {
			//获取状态条数量
			getbarsNum(){
				apiGetBar().then(res =>{
					this.list.forEach((item)=>{
						res.list.forEach(item2 =>{
							if(item.type == item2.type){
								item.cate_count = item2.count
							}
						})
					})
				})
			},
			change(event) {
				let index;
				event.detail ? index = event.detail.current : index = event
				this.current = Number(index)
				this.$refs.mescrollRef[this.current].mescroll.resetUpScroll()
			},
			//发货
			toDispath(id) {
				const params = {
					id: id,
					send_type: '',
					invoice_no: '',
					shipping_id: '',
				}
				apiOrderDelivery({
					...params
				})
				this.$refs.uToast.show({
					title: '发货成功',
					type: 'success'
				})
				this.current = 3

			},

			upCallback(page) {
				const index = this.current;
				const pageNum = page.num
				const pageSize = page.size
				
				this.getbarsNum()

				apiOrderList({
					goods_name: this.keyword,
					type: this.list[index].type,
					page_no: pageNum,
					page_size: pageSize,
				}).then(({
					list,
					size,
					more,
					count,
				}) => {
					// 如果是第一页或是搜索时需手动置空列表
					if (pageNum == 1 || this.keyword) this.list[index].lists = []
					const hasNext = !!more;
					// 重置列表数据
					this.count = count
					this.list[index].cate_count = count
					this.list[index].lists = [...this.list[index].lists, ...list]
					this.$refs.mescrollRef[index].mescroll.endSuccess(list.length, hasNext);
				}).catch((err) => {
					console.log(err)
					this.mescroll.endErr()
				})
			},

			copy(content) {
				copy(content)
			},
			//打印订单
			toPrint(id) {

			},
			reconnect() {
				uni.showLoading({
					mask: true,
					title: '正在连接设备' + this.deviceId
				})
				bluetooth.reconnect();
			},
			//搜索周边设备
			startBluetoothDeviceDiscovery() {
				uni.showLoading({
					title: '蓝牙搜索中'
				})

				let self = this;
				self.devicesList = [];

				setTimeout(() => {
					uni.startBluetoothDevicesDiscovery({
						success: res => {
							uni.onBluetoothDeviceFound(devices => {
								//console.log("发现设备: " + JSON.stringify(devices));
								//不重复,就添加到devicesList中,
								if (!self.devicesList.some(item => {
										return item.deviceId === devices.devices[0]
											.deviceId
									})) {
									self.devicesList.push(devices.devices[0])
								}
							});
						},
						fail: res => {
							uni.hideLoading();
							uni.showToast({
								title: `搜索设备失败` + JSON.stringify(err),
								icon: "none"
							})
						}
					})
				}, 200)
			},

			//停止搜索蓝牙设备
			stopBluetoothDevicesDiscovery() {
				uni.hideLoading();
				bluetooth.stopBluetoothDevicesDiscovery();
			},


			//选中设备
			async select_deviceId(item) {
				this.deviceId = item.deviceId;
				bluetooth.deviceId = item.deviceId;
				uni.setStorageSync('deviceId', bluetooth.deviceId);

				this.serviceList = [];

				try {
					//1.链接设备
					await bluetooth.createBLEConnection();

					uni.showLoading({
						title: '正在获取蓝牙设备服务'
					})
					//2.寻找服务
					await bluetooth.getBLEDeviceServices().then(res => {
						uni.hideLoading()
						this.serviceList = res;
					});
				} catch (e) {
					uni.hideLoading()
					console.log("e: " + JSON.stringify(e));
				}
			},

			//选中服务
			async select_service(res) {
				let self = this;
				bluetooth.serviceId = res.uuid;
				uni.setStorageSync('serviceId', res.uuid);
				try {
					let result = await bluetooth.getBLEDeviceCharacteristics();
					setTimeout(function() {
						uni.showToast({
							title: "已连接打印机，请测试打印",
							icon: "none"
						})
					}, 500);

				} catch (e) {
					console.log("e: " + JSON.stringify(e));
				}
			},

			//打印一次
			pickUpOnce(id) {
				uni.showToast({
					title: "正在为您打印...",
					mask: true,
					icon: "none",
					duration: 2000
				})
				bluetooth.notifyBLECharacteristicValue();
				let self = this;
				setTimeout(() => {
					self.writeBLECharacteristicValue(id);
				}, 500);
			},

			//写入控制命令
			async writeBLECharacteristicValue(id) {
				// 如果您有打印二维码需求，添加微信chengjn1314咨询
				let printerJobs = new PrinterJobs();
				printerJobs
					.setSize(1, 1)
					.print(printerUtil.fillAround('捕乐生活' + id + '#'))
					.print('')
					.setAlign('lt')
					.print('油品名称：92#汽油')
					.print('用户卡号：00000259')
					.print('加油数量：48.07升')
					.print('油品价格：8.05元')
					.print('加油金额：387元')
					.print('结算方式：用户卡')
					.print('卡余额：413.87元')
					.print('单位名称：供电局')
					.print('油站名称：桂通石油桥头加油站')
					.print('加油时间：2022-10-13 11：34：59')
					.print('')
					.print(printerUtil.fillAround('谢谢惠顾'))
					// .print(util.formatTime(new Date()))
					// .print(printerUtil.fillLine())
					.println();
				let buffer = printerJobs.buffer();
				this.printbuffs(buffer);
			},

			printbuffs(buffer) {
				// 1.并行调用多次会存在写失败的可能性
				// 2.建议每次写入不超过20字节
				// 分包处理，延时调用
				const maxChunk = 20;
				const delay = 20;
				for (let i = 0, j = 0, length = buffer.byteLength; i < length; i += maxChunk, j++) {
					let subPackage = buffer.slice(i, i + maxChunk <= length ? (i + maxChunk) : length);
					setTimeout(this.printbuff, j * delay, subPackage);
				}
			},

			printbuff(buffer) {
				bluetooth.writeBLECharacteristicValue(buffer);
			},

			async openFunc(item, action) {
				if (action == 'recycle') {
					const res = await apiOrderLogistics({
						id: item.id
					})
					this.logistics = res;
				}

				this.curData = item;
				this.action = action;
				this[action] = true;
			},

			// 操作订单
			async orderSetting() {
				let id = this.curData.id,
					action = this.action

				if (action == 'close') {
					await apiOrderClose({
						id
					})
				} else if (action == 'del') {
					await apiOrderDelete({
						id
					})
				} else if (action == 'confirm') {
					await apiOrderConfirm({
						id
					})
				}

				this.$refs.mescrollRef[this.current].mescroll.resetUpScroll()
				this.$refs.uToast.show({
					title: '操作成功',
					type: 'success'
				})
			}
		},

		onShow() {
			// getApp().globalData.reviseTabbarByUserType();
			// 使用防抖是为了防止v-show的时候出发多条数据，所以使用防抖触发多次的时候可以只成为触发一次，优化性能请求
			this.upCallback = debounce(this.upCallback, 200, this)
			this.$nextTick(() => {
				this.$refs.mescrollRef[this.current].mescroll.resetUpScroll()
			})

			uni.getSystemInfo({
				success: (res) => {
					this.height = res.windowHeight - 107 + 'px';
				}
			});
			if (uni.getStorageSync('curId')) {
				this.current = 3
			}
			getNewRemind().then(res =>{ //1：有新订单，0：无新订单。
				// console.log('new',res)
				if(res.is_new == 1){
					audibleAlert()
				}else{
					return false
				}
			})
		},
		onHide() {
			uni.removeStorageSync('curId')
		}
	}
</script>


<style lang="scss">
	/*根元素需要有固定的高度*/
	page {
		height: 100%;
		box-sizing: border-box;

		.header {
			padding: 16rpx 30rpx;
		}

		.nav {
			padding: 15rpx 0;
		}

		.section {
			overflow: hidden;

			.title {
				padding: 20rpx;
			}

			.btn {
				margin-top: 20rpx;
				margin-left: 20rpx;
				width: 180rpx;
				height: 64rpx;
				font-size: $-font-size-sm;
			}

			.solid {
				color: $-color-white;
				background-color: $-color-primary;
			}

			.hollow {
				color: $-color-lighter;
				border: 1px solid #DBDBDB;
			}


		}

		.copy {
			font-size: $-font-size-xs;
			margin-left: 20rpx;
			padding: 4rpx 10rpx;
			border-radius: 4rpx;
			color: $-color-primary;
			background-color: rgba(64, 175, 250, .1);
		}
	}
</style>